$(function(){
	var roleGrid = $("#roleGrid");
    var rolePermissionPanel = $("#rolePermissionPanel");
    var rolePermissionTree = $("#rolePermissionTree");
    var currentRow;
	//初始化
	roleGrid.datagrid({
		url:'role/list',
		fit:true,
		singleSelect: true,
		rownumbers:true,
		fitColumns:true,
		pagination : true,// 是否显示分页栏
		columns : [ [ {
			field : 'name',
			title : '角色名称',
			align : 'center',
			width : 180
		},{
			field: 'roleKey',
			title: '标识', 
			width: 150
		},{
			field : 'remark',
			title : '备注',
			align : 'center',
			width : 100
		}, {
	        field: 'enable', 
	        title: '状态', 
	        width: 80, 
	        align: 'center', 
	        formatter: function (val) {
	            return val ? "可用" : "禁用";
	          }
	     },{
			field : 'ac',
			title : '操作',
			width : 100,
			align : 'center',
			formatter:function(value,row,index){
				var bts = [];
				bts.push('<a data-index="'+index+'" class="ctr edit">编辑</a>');
				bts.push('<a data-id="'+row.id+'" data-index="'+index+'" class="ctr delete">删除</a>');
				return bts.join('');
			}
		} ] ],
		toolbar:[
		     {
		    	 iconCls:'icon-add',
		    	 text:"添加角色",
		    	 handler:function(){
		    		 roleForm();
		    	 }
		     }
		         ],
	     onSelect: function (index, row) {
	         //记录当前选中行
	         currentRow = row;
	
	         rolePermissionPanel.panel("setTitle", "为[" + row.name + "]分配权限");
	
	         //取消以前已经选中的项目
	         $.each(rolePermissionTree.tree("getChecked"), function () {
	           rolePermissionTree.tree("uncheck", this.target)
	         });
	
	         //加载当前选择角色的已有权限
	         $.get("/role/permission/" + row.id, function (data) {
	           $.each(data, function () {
	             var node = rolePermissionTree.tree('find', this.id);
	             //只当前权限是树的叶子节点时才执行节点的check方法进行选择
	             if (rolePermissionTree.tree('isLeaf', node.target)) {
	               rolePermissionTree.tree('check', node.target)
	             }
	           });
	         });
	       }
		
	});
	
	var name = $("#role");

	// 检索按钮事件
	$("#roleSearch").on('click', function() {
		roleGrid.datagrid("load", {
			name : "%" + name.val() + "%"
		});
	});

	
	var form = $("#roleSearchForm"); 

	$("#roleReset").on('click', function() {
		form.form('clear');
		// 清除查询参数
		roleGrid.datagrid("load", {});
	});
	
	var gridPanel = roleGrid.datagrid("getPanel");
	gridPanel.on("click", "a.edit", function() {
		var index = this.dataset.index;
		// 如果只有下标，没有id的情况，要获取id
		var rows = roleGrid.datagrid("getRows");
		// 同下标获取对应行的数据对象
		var id = rows[index].id;
		roleForm(id);
	}).on("click", "a.delete", function() {
		// 获取data-xxx绑定的标签属性数据
		var index = this.dataset.index;
		var id = this.dataset.id;
		$.messager.confirm("提示", "您确定要删除此数据?", function(r) {
			// 点击了确定按钮，r返回的结果为true
			if (r) {
				$.get("role/delete/" + id, function(rs) {
					if (rs.success) {
						// 刷新表格
						roleGrid.datagrid("reload");
					} else {
						$.message.alert("提示", rs.message);
					}
				});
			}
		});
	});
	
	
	
	/**
	 * 用户表单，新建和编辑都调用此方法
	 */
	function roleForm(id){
		// 创建窗口
		var dialog = $("<div/>").dialog({
			href : 'role/add_role' + (id ? ("/" + id) : ""),
			title:"部门信息",
			height:335,
			width:360,
			modal : true,
			onClose : function() {
				// 窗口关闭的同时销毁此窗口
				$(this).dialog("destroy");
			},
			buttons : [ {
				iconCls : 'icon-save',
				text : '保存',
				handler : function() {
					// 获取到表单对象
					var roleForm = $("#roleForm");
					// 校验表单
					if (roleForm.form('validate')) {
						// serialize方法可以获取到表单所有数据
						$.post("role/save", roleForm.serialize(), function(rs) {
							if (rs.success) {
								//刷新数据表格
								roleGrid.datagrid("reload");
								//关闭窗口
								dialog.dialog("close");
							} else {
								$.messager.alert("提示", rs.message);
							}
						});
					}
				}
			} ]
		});
	}
	  rolePermissionTree.tree({
		    url: '/role/permission/tree',
		    checkbox: true
		  });
	//权限保存的按钮时间
	  $("#rolePermissionSave").on('click', function () {
	    if (currentRow) {
	      //获取打钩和实心的节点
	      var nodes = rolePermissionTree.tree("getChecked", ["checked", "indeterminate"]);
	      var permissionIds = [];
	      $.each(nodes, function () {
	        permissionIds.push(this.id);
	      });

	      var params = "roleId=" + currentRow.id + "&permissionId=" + permissionIds.join("&permissionId=");

	      $.post("/role/permission/save", params, function (resp) {
	        if (resp.success) {
	          $.messager.alert("提示", "授权成功！");
	        }
	      })
	    }
	  });
});